import { CalendarOutlined, FullscreenOutlined, SearchOutlined } from '@ant-design/icons';
import { Button, DatePicker, Empty, Input, Select, Skeleton, Space, Tooltip } from 'antd';
import { CalendarPicker, Picker } from 'antd-mobile';
import dayjs from 'dayjs';
import React, { useEffect, useState } from 'react';

import reportService from '@/api/services/reportService';
import {
  wordFreqItem,
  statisticsListItem,
  regionalstats,
  userActiveItem,
  candidatequality,
  highschoolconsultations,
  popularmajor,
  popularpercentages,
  recommendedlocations,
  recommendedtimes,
  topquestions,
  hotword,
} from '@/common/types';
import { SvgIcon } from '@/components/icon';
import Markdown from '@/components/markdown';
import useWindowWidth from '@/hooks/event/use-window-width';
import { useRouter } from '@/router/hooks';
import { useManagePage } from '@/store/configStore';
import { useThemeToken } from '@/theme/hooks';

import ChinaMap from './components/ChinaMap';
import ConsultationStatisticsBar from './components/ConsultationStatisticsBar';
import HighschoolBarModel from './components/HighschoolBarModel';
import HotTreemap from './components/HotTreemap';
import LineChart from './components/LineChart';
import UserActiveStatuLine from './components/UserActiveStatuLine';
import UserActiveStatuLineModel from './components/UserActiveStatuLineModel';
import Yibiaopan from './components/Yibiaopan';

const { RangePicker } = DatePicker;

const Report2 = () => {
  // const { id } = useParams();
  const searchParams = new URLSearchParams(location.search);
  const id = searchParams.get('appId');
  const { isPc } = useWindowWidth();
  const [statisticsLoading, setStatisticsLoading] = useState(false);
  const [statisticsAllLoading, setStatisticsAllLoading] = useState(false);
  const [totalUsers, setTotalUsers] = useState(0);
  const [selectedRole, setSelectedRole] = useState('');
  const [totalQuestions, setTotalQuestions] = useState(0);
  const [totalConversation, setTotalConversation] = useState(0);
  const [totalSatisfaction, setTotalSatisfaction] = useState(100);
  const [chartData, setChartData] = useState<statisticsListItem[]>([]);
  const [wordFreqLoading, setWordFreqLoading] = useState(false);
  const [wordCloudData, setWordCloudData] = useState<wordFreqItem[]>([]);

  const [userActiveData, setUserActiveData] = useState<userActiveItem[]>([
    { name: '1', value: 10 },
    { name: '1', value: 10 },
    { name: '1', value: 10 },
    { name: '1', value: 10 },
    { name: '1', value: 10 },
  ]);
  const [schoolData, setSchoolData] = useState<userActiveItem[]>([
    { name: '1', value: 10 },
    { name: '1', value: 10 },
    { name: '1', value: 10 },
    { name: '1', value: 10 },
    { name: '1', value: 10 },
  ]);

  const [logoutVisible, setLogoutVisible] = useState(false);
  const [highschoolBarVisible, setHighschoolBarVisible] = useState(false);

  const [dateRangeAll, setDateRangeAll] = useState<[dayjs.Dayjs, dayjs.Dayjs] | undefined>(
    undefined,
  );

  const [candidateQuality, setCandidateQuality] = useState<candidatequality>({
    reason: '',
    result: '',
  });
  const [highschoolConsultations, setHighschoolConsultations] = useState<highschoolconsultations[]>(
    [],
  );
  const [popularMajors, setPopularMajors] = useState<popularmajor[]>([]);
  const [popularPercentages, setPopularPercentages] = useState<popularpercentages[]>([]);
  const [recommendedLocations, setRecommendedLocations] = useState<recommendedlocations[]>([]);
  const [recommendedtimes, setRecommendedtimes] = useState<recommendedtimes[]>([]);
  const [topQuestions, setTopQuestions] = useState<topquestions[]>([]);
  const [regionalstats, setRegionalstats] = useState<regionalstats[]>([]);
  const [regionalpercentages, setRegionalpercentages] = useState<regionalstats[]>([]);
  const [dashboardActive, setDashboardActive] = useState<regionalstats[]>([]);
  const [dashboardActiveDay, setDashboardActiveDay] = useState<regionalstats[]>([]);

  const [hotwords, setHotwords] = useState<hotword[]>([]);
  const [historyQuestions, setHistoryQuestions] = useState<hotword[]>([]);
  const [Achotwords, setAcHotwords] = useState('');
  const [searchHotwords, setSearchHotwords] = useState('');
  const { colorBgBase, colorPrimary } = useThemeToken();
  const [visible, setVisible] = useState(false);
  const [zhaoshengLoading, setZhaoshengLoading] = useState(false);
  const [zhaosHistoryLoading, setZhaosHistoryLoading] = useState(false);
  const [zhaosDashboardActiveLoading, setZhaosDashboardActiveLoading] = useState(false);
  const router = useRouter();
  const managePage = useManagePage();

  const [visiblemobile, setVisiblemobile] = useState(false);
  const [value, setValue] = useState<(string | null)[]>(['M']);
  const [selectedOption, setSelectedOption] = React.useState(null);

  const handleLogoutConfirm = () => {
    setLogoutVisible(false);
  };

  const [dateRange, setDateRange] = useState<[dayjs.Dayjs, dayjs.Dayjs]>([
    dayjs().subtract(7, 'day'),
    dayjs(),
  ]);

  useEffect(() => {
    if (id) {
      fetchData(id, dateRange[0].format('YYYY-MM-DD'), dateRange[1].format('YYYY-MM-DD'));
    }
  }, [id, dateRange, selectedRole]);

  useEffect(() => {
    if (id) {
      statisticsAll(id);
      fetchwordFreq(id);
      getzhaoshengDashboardActive(id);
      getzhaoshengDashboardData(id);
      getHistoryQuestions(id);
    }
  }, [id, selectedRole]);

  useEffect(() => {
    getHistoryQuestions(id);
    getzhaoshengDashboardActive(id);
    getzhaoshengDashboardData(id);
    statisticsAll(id);
    dateRangeAll &&
      fetchData(id, dateRangeAll[0].format('YYYY-MM-DD'), dateRangeAll[1].format('YYYY-MM-DD'));
  }, [dateRangeAll]);

  useEffect(() => {
    getHistoryQuestions(id);
  }, [searchHotwords, Achotwords]);

  const onRangePickerChange = (dates: any) => {
    console.log(dates);

    if (dates && dates.length === 2) {
      setDateRangeAll([dates[0], dates[1]]);
    }

    if (!dates) return;
    setSelectedOption(null);
  };

  const changeHotword = (type: string) => {
    console.log('type', type);
    setAcHotwords(type);
  };

  const getHistoryQuestions = async (id: string) => {
    try {
      setZhaosHistoryLoading(true);
      const res = await reportService.zhaoshengHistoryQuestions(id, {
        start_time: dateRangeAll ? dateRangeAll[0].format('YYYY-MM-DD') : undefined,
        end_time: dateRangeAll ? dateRangeAll[1].format('YYYY-MM-DD') : undefined,
        label_text: Achotwords,
        search_text: searchHotwords,
        page: 1,
        page_size: 1000,
      });
      console.log('历史==========', res.allData);

      setHistoryQuestions(res.allData);
    } catch (err) {
      console.log(err);
    } finally {
      setZhaosHistoryLoading(false);
    }
  };

  const getCandidateQuality = (data: any) => {
    if (!data || typeof data !== 'object') {
      return { result: '良', reason: '暂无评估:咨询考生较少,无法进行评估' };
    }

    return {
      result: data.result || '良',
      reason: data.reason || '暂无评估:咨询考生较少,无法进行评估',
    };
  };

  const processRecommendedTimes = (data: any[]) => {
    const DEFAULT_RECOMMENDED_TIME = {
      name: '高峰期',
      time_range: '-',
      suggest: '咨询考生较少,无法进行分析',
    };
    const DEFAULT_RECOMMENDED_TIME_LOW = {
      name: '低谷期',
      time_range: '-',
      suggest: '咨询考生较少,无法进行分析',
    };
    // 确保是数组
    const validData = Array.isArray(data) ? [...data] : [];

    // 填充至最少2个元素
    while (validData.length <= 0) {
      return [DEFAULT_RECOMMENDED_TIME, DEFAULT_RECOMMENDED_TIME_LOW];
    }

    // 确保每个元素都有完整字段
    return validData.map((item, index) => ({
      name: item.name,
      time_range: item.time_range,
      suggest: item.suggest,
    }));
  };

  const processRecommendedLocations = (data: any[]) => {
    const DEFAULT_RECOMMENDED_LOCATION = {
      location: '咨询考生较少,无法进行推荐',
      score: 0,
      reason: '暂无数据',
    };
    // 确保是数组
    const validData = Array.isArray(data) ? [...data] : [];

    // 填充至最少10个元素
    while (validData.length <= 0) {
      return [DEFAULT_RECOMMENDED_LOCATION];
    }

    // 确保每个元素都有完整字段
    return validData.map((item) => ({
      location: item.location || DEFAULT_RECOMMENDED_LOCATION.location,
      score: typeof item.score === 'number' ? item.score : DEFAULT_RECOMMENDED_LOCATION.score,
      reason: item.reason || DEFAULT_RECOMMENDED_LOCATION.reason,
    }));
  };

  const processTopQuestions = (data: any[]) => {
    const DEFAULT_TOP_QUESTION = {
      question: '咨询考生较少,无法进行评估',
      frequency: 0,
    };
    // 确保是数组
    const validData = Array.isArray(data) ? [...data] : [];

    // 填充至最少10个元素
    while (validData.length <= 0) {
      return [DEFAULT_TOP_QUESTION];
    }

    // 确保每个元素都有完整字段
    return validData.map((item) => ({
      question: item.question || DEFAULT_TOP_QUESTION.question,
      frequency:
        typeof item.frequency === 'number' ? item.frequency : DEFAULT_TOP_QUESTION.frequency,
    }));
  };

  const getzhaoshengDashboardData = async (id: string) => {
    try {
      setZhaoshengLoading(true);
      const res = await reportService.zhaoshengDashboardData(id, {
        start: dateRangeAll ? dateRangeAll[0].format('YYYY-MM-DD') : undefined,
        end: dateRangeAll ? dateRangeAll[1].format('YYYY-MM-DD') : undefined,
      });
      console.log('res=============', res);

      setCandidateQuality(getCandidateQuality(res['candidate-quality']));
      setHighschoolConsultations(res['highschool-consultations']);
      setPopularMajors(res['popular-majors'].majors);

      const majorPercentages = res['popular-majors'].percentages || [];
      const filledmajorPercentages = [...majorPercentages];
      while (filledmajorPercentages.length < 4) {
        filledmajorPercentages.push({ major: '-', percentage: 0 });
      }
      setPopularPercentages(filledmajorPercentages);

      // setRecommendedLocations(res['recommended-locations'])
      setRecommendedLocations(processRecommendedLocations(res['recommended-locations']));

      setRecommendedtimes(processRecommendedTimes(res['recommended-times']));

      setTopQuestions(processTopQuestions(res['top-questions']));
      setRegionalstats(res['regional-stats'].regions);
      // setRegionalpercentages(res['regional-stats'].percentages)
      const rawPercentages = res['regional-stats'].percentages || [];
      const filledPercentages = [...rawPercentages];

      // 填充到4个元素
      while (filledPercentages.length < 4) {
        filledPercentages.push({ region: '-', percentage: 0 });
      }

      setRegionalpercentages(filledPercentages);

      const newhotwords = res['hot-words'].dataList.map((item) => {
        return {
          label: item.word,
          value: item.word,
        };
      });
      setHotwords(newhotwords);
      setAcHotwords(res['hot-words'].data_list[0].word);
    } catch (err) {
      console.log(err);
    } finally {
      setZhaoshengLoading(false);
    }
  };

  const getzhaoshengDashboardActive = async (id: string) => {
    try {
      setZhaosDashboardActiveLoading(true);
      const res = await reportService.zhaoshengDashboardActive(id, {
        start: dateRangeAll ? dateRangeAll[0].format('YYYY-MM-DD') : undefined,
        end: dateRangeAll ? dateRangeAll[1].format('YYYY-MM-DD') : undefined,
      });
      console.log('getLast24HoursData=============', res, getLast24HoursData(res));
      setDashboardActive(res);
    } catch (err) {
      console.log(err);
    } finally {
      setZhaosDashboardActiveLoading(false);
    }
  };

  const fetchwordFreq = async (id: string) => {
    try {
      setWordFreqLoading(true);
      const response = await reportService.wordFreqV2(id, selectedRole);
      console.log('wordFreq', response);
      setWordCloudData(response?.wordFreq || []);
    } catch (error) {
    } finally {
      setWordFreqLoading(false);
    }
  };

  const fetchData = async (id: string, startDate: string, endDate: string) => {
    try {
      setStatisticsLoading(true);
      const response = await reportService.statisticsListV2(
        id,
        {
          start: startDate,
          end: endDate,
        },
        selectedRole,
      );

      response.forEach((item) => {
        // 处理边界情况
        if (item.questionCount <= 0) {
          item.satisfaction = '100'; // 默认值
          return;
        }

        // 计算原始值并确保在[0, 100]范围内
        const rawValue = (1 - item.unLikeCount / item.questionCount) * 100;
        const clampedValue = Math.max(0, Math.min(100, rawValue));

        item.satisfaction = clampedValue.toFixed(2);
      });
      console.log('fetchData', response);
      setChartData(response);
    } catch (error) {
    } finally {
      setStatisticsLoading(false);
    }
  };

  const statisticsAll = async (id: string) => {
    try {
      setStatisticsAllLoading(true);
      const response = await reportService.statisticsAllV2(id, selectedRole);
      console.log('statisticsAll', response);
      setTotalUsers(response?.userCount ?? 0);
      setTotalQuestions(response?.questionCount ?? 0);
      setTotalConversation(response?.total ?? 0);
      setTotalSatisfaction(
        response?.questionCount ? 100 * (1 - response?.unLikeCount / response?.questionCount) : 0,
      );
    } catch (error) {
    } finally {
      setStatisticsAllLoading(false);
    }
  };

  const handleChange = (value: string) => {
    setSelectedOption(value);
    console.log(value);
    if (value == '7day') {
      setDateRangeAll([dayjs().subtract(7, 'day'), dayjs()]);
    } else if (value == '30day') {
      setDateRangeAll([dayjs().subtract(30, 'day'), dayjs()]);
    } else if (value == '2month') {
      setDateRangeAll([dayjs().subtract(2, 'month'), dayjs()]);
    }
  };
  const handleDateChange = (dates: any) => {
    if (dates && dates.length === 2) {
      // setDateRange([dates[0], dates[1]]);
      setDateRangeAll([dates[0], dates[1]]);
    }
  };

  const boxstyle = {
    padding: '20px 20px',
    marginTop: '16px',
    backgroundColor: '#FBFCFF',
    borderRadius: '20px',
    // weidth: "calc((100% - 16px) / 3)",
    width: '100%',
    height: '300px',
  };

  const boxstyle2 = {
    padding: '20px 20px',
    marginTop: '16px',
    backgroundColor: '#FBFCFF',
    borderRadius: '20px',
    width: '100%',
    height: isPc ? '630px' : '550px',
  };

  const handleIconClick = () => {
    setVisible(true); // 点击图标时显示日期选择器
  };

  const getLast24HoursData = (data) => {
    if (!data || data.length === 0) return [];

    // 获取当前时间
    const now = new Date();
    // 计算24小时前的时间
    const twentyFourHoursAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);

    // 过滤出最近24小时的数据
    return data.filter((item) => {
      const itemDate = new Date(item.active_hours);
      return itemDate >= twentyFourHoursAgo;
    });
  };

  const basicColumns = [
    [
      { label: '周一', value: 'Mon' },
      { label: '周二', value: 'Tues' },
      { label: '周三', value: 'Wed' },
      { label: '周四', value: 'Thur' },
      { label: '周五', value: 'Fri' },
    ],
  ];

  return (
    <div className="h-full w-full p-4" style={{ overflowY: 'auto', scrollbarWidth: 'none' }}>
      <div
        style={{
          display: 'flex',
          flexDirection: isPc ? 'row' : 'row',
          alignItems: 'center',
          justifyContent: 'space-between',
        }}
      >
        <div className="flex shrink-0 items-center ">
          {/* <SvgIcon style={{ cursor: 'pointer' }} icon="Vector" color='black' size={35} onClick={() => {
            router.push(managePage);
          }} />
          <div className='ml-4' >{"应用看板"}</div> */}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end' }}>
          {isPc ? (
            <RangePicker onChange={onRangePickerChange} value={dateRangeAll} />
          ) : (
            <div>
              <CalendarOutlined
                onClick={handleIconClick}
                style={{ fontSize: '24px', cursor: 'pointer', color: colorPrimary }}
              />
              {visible && (
                <CalendarPicker
                  visible={visible}
                  className="custom-calendar-picker"
                  style={{
                    '--adm-color-primary': colorPrimary,
                  }}
                  min={new Date(2024, 1, 1)}
                  selectionMode="range"
                  onClose={() => setVisible(false)}
                  onMaskClick={() => setVisible(false)}
                  onChange={(val) => {
                    if (val?.length == 2) {
                      const dayjsDate0 = dayjs(val[0]);
                      const dayjsDate1 = dayjs(val[1]);
                      handleDateChange([dayjsDate0, dayjsDate1]);

                      setSelectedOption(null);
                    }
                  }}
                />
              )}
            </div>
          )}

          <Select
            placeholder="请选择"
            style={{ width: 120, marginLeft: '10px' }}
            onChange={handleChange}
            value={selectedOption}
            options={[
              { value: '7day', label: '近7天' },
              { value: '30day', label: '近30天' },
              { value: '2month', label: '近2个月' },
            ]}
          />
        </div>
      </div>

      <div className={`${isPc ? 'flex' : ''}`}>
        <div style={boxstyle} className="mr-5">
          {zhaoshengLoading ? (
            <Skeleton active paragraph={{ rows: 6 }} />
          ) : (
            <div>
              <div className="flex items-center">
                <SvgIcon color="#1B6DFA" icon="Ellipse" />
                <div
                  style={{
                    color: '#1D2129',
                    fontSize: '20px',
                    fontWeight: 'bold',
                    marginLeft: '10px',
                  }}
                >
                  考生的总体质量分析
                </div>
              </div>

              <Yibiaopan data={candidateQuality} />

              {/* <div style={{ display: "flex", justifyContent: "center", alignItems: "center", color: "#00E096", fontSize: "48px", width: "100%", height: "160px" }}>{candidateQuality.result}</div> */}
              {/* <p title={candidateQuality.reason} style={{
                textAlign: "center",
                display: "-webkit-box",
                WebkitBoxOrient: "vertical",
                WebkitLineClamp: 3, // 限制为2行
                overflow: "hidden",
                textOverflow: "ellipsis",
                maxWidth: "100%", // 确保有宽度限制
                marginTop: "-30px"
              }}>{candidateQuality.reason}</p> */}

              <div
                style={{
                  height: '100px',
                  marginTop: '-70px',
                  overflowY: 'auto',
                  scrollbarWidth: 'none',
                }}
              >
                <Markdown source={candidateQuality.reason} />
              </div>
            </div>
          )}
        </div>

        <div style={boxstyle} className="mr-5">
          {zhaoshengLoading ? (
            <Skeleton active paragraph={{ rows: 6 }} />
          ) : (
            <div>
              <div className="flex items-center">
                <SvgIcon color="#1B6DFA" icon="Ellipse" />
                <div
                  style={{
                    color: '#1D2129',
                    fontSize: '20px',
                    fontWeight: 'bold',
                    marginLeft: '10px',
                  }}
                >
                  咨询闲忙期
                </div>
              </div>
              {recommendedtimes && recommendedtimes.length > 0 ? (
                <div className="flex h-full ">
                  <div
                    style={{
                      backgroundColor: '#F7F8FA',
                      borderRadius: '10px',
                      marginRight: '16px',
                    }}
                    className="mt-[10px] flex h-[220px] w-full flex-col items-center justify-center pr-4"
                  >
                    <div className="flex h-[48px] w-[48px] items-center justify-center rounded-[10px] bg-white">
                      <SvgIcon size={24} icon="Frame" />
                    </div>

                    <div
                      style={{
                        color: '#DB1D1D',
                        fontSize: '20px',
                        fontWeight: 'bold',
                        marginTop: '10px',
                        marginBottom: '10px',
                      }}
                    >
                      {recommendedtimes[0].name}
                    </div>
                    {/* <p >{recommendedtimes[0].time_range}</p> */}
                    <p
                      style={{
                        textAlign: 'center',
                        display: '-webkit-box',
                        WebkitBoxOrient: 'vertical',
                        WebkitLineClamp: 2, // 限制为2行
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        maxWidth: '100%', // 确保有宽度限制
                        margin: '0 auto',
                      }}
                    >
                      {recommendedtimes[0].suggest}
                    </p>
                  </div>

                  <div
                    style={{ backgroundColor: '#F7F8FA', borderRadius: '10px' }}
                    className="mt-[10px]  flex h-[220px] w-full flex-col items-center justify-center pl-4"
                  >
                    <div className="flex h-[48px] w-[48px] items-center justify-center rounded-[10px] bg-white">
                      <SvgIcon size={24} icon="Frame2" />
                    </div>

                    <div
                      style={{
                        color: '#21B9B9',
                        fontSize: '20px',
                        fontWeight: 'bold',
                        marginTop: '10px',
                        marginBottom: '10px',
                      }}
                    >
                      {recommendedtimes[1].name}
                    </div>
                    {/* <p>{recommendedtimes[1].time_range}</p> */}
                    <p
                      style={{
                        textAlign: 'center',
                        display: '-webkit-box',
                        WebkitBoxOrient: 'vertical',
                        WebkitLineClamp: 2, // 限制为2行
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        maxWidth: '100%', // 确保有宽度限制
                        margin: '0 auto',
                      }}
                    >
                      {recommendedtimes[1].suggest}
                    </p>
                  </div>
                </div>
              ) : (
                <Empty description="暂无数据" />
              )}
            </div>
          )}
        </div>

        <div style={boxstyle}>
          {zhaoshengLoading ? (
            <Skeleton active paragraph={{ rows: 6 }} />
          ) : (
            <div>
              <div className="flex items-center">
                <SvgIcon color="#1B6DFA" icon="Ellipse" />
                <div
                  style={{
                    color: '#1D2129',
                    fontSize: '20px',
                    fontWeight: 'bold',
                    marginLeft: '10px',
                  }}
                >
                  推荐招生铺位置
                </div>
              </div>

              {recommendedLocations && recommendedLocations.length > 0 ? (
                <div
                  className="mt-2 grid grid-cols-2 gap-x-2 gap-y-2"
                  style={{
                    gridAutoFlow: 'column',
                    gridTemplateRows: 'repeat(5, 40px)',
                    gridAutoRows: '40px', // 设置每行高度
                  }}
                >
                  {recommendedLocations.map((item, index) => (
                    <div key={index} className="flex items-center" style={{ fontSize: '16px' }}>
                      {index < 3 ? (
                        <div
                          style={{
                            flexShrink: 0,
                            fontWeight: 'bold',
                            color: index == 0 ? '#E24741' : '#ED7943',
                            width: '24px',
                            height: '24px',
                            display: 'flex',
                            justifyContent: 'center',
                            alignItems: 'center',
                            backgroundColor: index == 0 ? '#FFECE8' : '#FFF2E8',
                            borderRadius: '50%',
                            marginRight: '8px',
                          }}
                        >
                          0{index + 1}
                        </div>
                      ) : (
                        <div
                          style={{
                            flexShrink: 0,
                            width: '24px',
                            height: '24px',
                            display: 'flex',
                            justifyContent: 'center',
                            alignItems: 'center',
                            borderRadius: '50%',
                            marginRight: '8px',
                          }}
                        >
                          {index !== 9 ? `0${index + 1} ` : index + 1}
                        </div>
                      )}
                      <span
                        style={{
                          overflow: 'hidden',
                          whiteSpace: 'nowrap',
                          textOverflow: 'ellipsis',
                          marginRight: '4px',
                        }}
                      >
                        {item.location}
                      </span>
                      <Tooltip title={item.reason}>
                        <div>
                          <SvgIcon icon="Framewh" />
                        </div>
                      </Tooltip>
                    </div>
                  ))}
                </div>
              ) : (
                <Empty description="暂无数据" />
              )}
            </div>
          )}
        </div>
      </div>

      <div className={`${isPc ? 'grid grid-cols-3 gap-5' : ''}`}>
        <div
          style={{
            padding: '20px 20px',
            marginTop: '16px',
            backgroundColor: '#FBFCFF',
            borderRadius: '20px',
            width: '100%',
            height: '630px',
          }}
          className="mr-5"
        >
          {zhaoshengLoading ? (
            <Skeleton active paragraph={{ rows: 8 }} />
          ) : (
            <div>
              <div className="flex items-center">
                <SvgIcon color="#1B6DFA" icon="Ellipse" />
                <div
                  style={{
                    color: '#1D2129',
                    fontSize: '20px',
                    fontWeight: 'bold',
                    marginLeft: '10px',
                  }}
                >
                  Top 10 问题
                </div>
              </div>
              {topQuestions && topQuestions.length > 0 && (
                <div className="mt-4 flex">
                  <tr className="w-10 leading-[42px]">#</tr>
                  <div className="w-full leading-[42px]">问题</div>
                  <tr className="w-20 leading-[42px]">提及数量</tr>
                </div>
              )}

              {topQuestions && topQuestions.length > 0 ? (
                <div>
                  {topQuestions.map((item, index) => (
                    <div
                      style={{
                        height: '50px',
                        display: 'flex',
                        alignItems: 'center',
                        width: '100%',
                        fontSize: '16px',
                        overflow: 'hidden',
                        whiteSpace: 'nowrap',
                        textOverflow: 'ellipsis',
                      }}
                      key={index}
                    >
                      {index < 3 ? (
                        <div
                          style={{
                            marginRight: '10px',
                            flexShrink: '0',
                            fontWeight: 'bold',
                            color: index == 0 ? '#E24741' : '#ED7943',
                            width: '24px',
                            height: '24px',
                            display: 'flex',
                            justifyContent: 'center',
                            alignItems: 'center',
                            backgroundColor: index == 0 ? '#FFECE8' : '#FFF2E8',
                            borderRadius: '50%',
                          }}
                        >
                          0{index + 1}
                        </div>
                      ) : (
                        <div
                          style={{
                            marginRight: '10px',
                            flexShrink: '0',
                            fontWeight: 'bold',
                            width: '24px',
                            height: '24px',
                            display: 'flex',
                            justifyContent: 'center',
                            alignItems: 'center',
                            borderRadius: '50%',
                          }}
                        >
                          {index !== 9 ? `0${index + 1} ` : index + 1}
                        </div>
                      )}
                      <div
                        title={item.question}
                        style={{
                          width: '100%',
                          overflow: 'hidden',
                          whiteSpace: 'nowrap',
                          textOverflow: 'ellipsis',
                        }}
                      >
                        {item.question}
                      </div>
                      <tr className="w-20  text-center " style={{ fontWeight: 'bold' }}>
                        {item.frequency}
                      </tr>
                    </div>
                  ))}
                </div>
              ) : (
                <div
                  style={{
                    height: '400px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                  }}
                >
                  <Empty description="暂无数据" />
                </div>
              )}
            </div>
          )}
        </div>

        <div style={boxstyle2} className="mr-5">
          {zhaoshengLoading ? (
            <Skeleton active paragraph={{ rows: 8 }} />
          ) : (
            <div>
              <div className="flex items-center">
                <SvgIcon color="#1B6DFA" icon="Ellipse" />
                <div
                  style={{
                    color: '#1D2129',
                    fontSize: '20px',
                    fontWeight: 'bold',
                    marginLeft: '10px',
                  }}
                >
                  访问地区统计
                </div>
              </div>
              <div style={{ display: 'flex', marginTop: isPc ? '10px' : '10px' }}>
                {regionalpercentages.map((item, index) => (
                  <div
                    className="flex h-[107px] flex-col items-center rounded-[10px] bg-[#F7F8FA]"
                    style={{
                      width: '100%',
                      fontSize: '16px',
                      marginRight: index == 3 ? '0px' : isPc ? '16px' : '6px',
                    }}
                    key={index}
                  >
                    <div className="text-[24px] font-bold leading-[60px]">{item.percentage}%</div>
                    <div style={{ fontSize: '14px' }}>{item.region}</div>
                  </div>
                ))}
              </div>
              <ChinaMap data={regionalstats} />
            </div>
          )}
        </div>

        <div style={boxstyle2}>
          {zhaoshengLoading ? (
            <Skeleton active paragraph={{ rows: 8 }} />
          ) : (
            <div>
              <div className="flex items-center">
                <SvgIcon color="#1B6DFA" icon="Ellipse" />
                <div
                  style={{
                    color: '#1D2129',
                    fontSize: '20px',
                    fontWeight: 'bold',
                    marginLeft: '10px',
                  }}
                >
                  热门专业
                </div>
              </div>
              <div style={{ display: 'flex', marginTop: isPc ? '10px' : '10px' }}>
                {popularPercentages.map((item, index) => (
                  <div
                    className="flex h-[107px] flex-col items-center rounded-[10px] bg-[#F7F8FA]"
                    style={{
                      width: '100%',
                      fontSize: '16px',
                      marginRight: index == 3 ? '0px' : isPc ? '16px' : '6px',
                    }}
                    key={index}
                  >
                    <div className="text-[24px] font-bold leading-[60px]">{item.percentage}%</div>
                    <div style={{ fontSize: '14px' }}>{item.major}</div>
                  </div>
                ))}
              </div>
              <HotTreemap data={popularMajors} />
            </div>
          )}
        </div>
      </div>

      <div className={`${isPc ? 'flex' : ''}`}>
        <div
          style={{
            padding: isPc ? '20px 20px' : '20px 10px',
            marginTop: '16px',
            backgroundColor: '#FBFCFF',
            borderRadius: '20px',
            width: '100%',
            height: '400px',
            // marginRight: '20px',
          }}
        >
          <div className="flex w-full items-center justify-between">
            {statisticsAllLoading ? (
              <Skeleton active paragraph={{ rows: 1 }} />
            ) : (
              <div style={{ display: 'flex', width: '100%', justifyContent: 'space-between' }}>
                <div
                  style={{
                    padding: isPc ? '8px 8px' : '8px 2px',
                    marginRight: '10px',
                    width: '100%',
                    height: isPc ? '106px' : '90px',
                    backgroundColor: '#F7F8FA',
                    borderRadius: '12px',
                  }}
                >
                  <span
                    className="statistic-digit"
                    style={{ fontSize: isPc ? '36px' : '20px', color: '#1D2129' }}
                  >
                    {totalUsers}
                  </span>
                  <br />

                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <SvgIcon
                      icon="reportline1"
                      size={isPc ? 18 : 14}
                      style={{ marginRight: isPc ? '8px' : '2px' }}
                    />
                    <span
                      className={`statistic-word ${isPc ? 'text-[16px]' : 'text-[12px]'}  ${
                        isPc ? 'mr-2' : 'mr-0'
                      } `}
                    >
                      用户数
                    </span>
                    {/* {isPc && <SvgIcon icon='Framewh'></SvgIcon>} */}
                  </div>
                </div>

                <div
                  style={{
                    padding: isPc ? '8px 8px' : '8px 2px',
                    marginRight: '10px',
                    width: '100%',
                    height: isPc ? '106px' : '90px',
                    backgroundColor: '#F7F8FA',
                    borderRadius: '12px',
                  }}
                >
                  <span
                    className="statistic-digit"
                    style={{ fontSize: isPc ? '36px' : '20px', color: '#1D2129' }}
                  >
                    {totalQuestions}
                  </span>
                  <br />

                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <SvgIcon
                      icon="reportline2"
                      size={isPc ? 18 : 14}
                      style={{ marginRight: isPc ? '8px' : '2px' }}
                    />
                    <span
                      className={`statistic-word ${isPc ? 'text-[16px]' : 'text-[12px]'}  ${
                        isPc ? 'mr-2' : 'mr-0'
                      } `}
                    >
                      对话数
                    </span>
                    {/* {isPc && <SvgIcon icon='Framewh'></SvgIcon>} */}
                  </div>
                </div>

                <div
                  style={{
                    padding: isPc ? '8px 8px' : '8px 2px',
                    marginRight: '10px',
                    width: '100%',
                    height: isPc ? '106px' : '90px',
                    backgroundColor: '#F7F8FA',
                    borderRadius: '12px',
                  }}
                >
                  <span
                    className="statistic-digit"
                    style={{ fontSize: isPc ? '36px' : '20px', color: '#1D2129' }}
                  >
                    {totalConversation}
                  </span>
                  <br />

                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <SvgIcon
                      icon="reportline3"
                      size={isPc ? 18 : 14}
                      style={{ marginRight: isPc ? '8px' : '2px' }}
                    />
                    <span
                      className={`statistic-word ${isPc ? 'text-[16px]' : 'text-[12px]'}  ${
                        isPc ? 'mr-2' : 'mr-0'
                      } `}
                    >
                      会话数
                    </span>
                    {/* {isPc && <SvgIcon icon='Framewh'></SvgIcon>} */}
                  </div>
                </div>

                <div
                  style={{
                    padding: isPc ? '8px 8px' : '8px 2px',
                    width: isPc ? '100%' : '130%',
                    height: isPc ? '106px' : '90px',
                    backgroundColor: '#F7F8FA',
                    borderRadius: '12px',
                  }}
                >
                  <span
                    className="statistic-digit"
                    style={{ fontSize: isPc ? '36px' : '20px', color: '#1D2129' }}
                  >
                    {totalSatisfaction.toFixed(2)}%
                  </span>
                  <br />

                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <SvgIcon
                      icon="reportline4"
                      size={isPc ? 18 : 14}
                      style={{ marginRight: isPc ? '8px' : '2px' }}
                    />
                    <span
                      className={`statistic-word ${isPc ? 'text-[16px]' : 'text-[12px]'}  ${
                        isPc ? 'mr-2' : 'mr-0'
                      } `}
                    >
                      平均满意度
                    </span>
                    {/* {isPc && <SvgIcon icon='Framewh'></SvgIcon>} */}
                  </div>
                </div>
              </div>
            )}
          </div>

          {statisticsLoading ? (
            <Skeleton active paragraph={{ rows: 5 }} style={{ padding: '10px' }} />
          ) : (
            <LineChart data={chartData} />
          )}
        </div>

        {/* <div style={{
          padding: "20px 20px", marginTop: "16px", backgroundColor: "#FBFCFF", borderRadius: "20px", width: isPc ? "40%" : "100%", height: "400px"
        }}>
          <div className='flex items-center'>
            <SvgIcon color='#1B6DFA' icon='Ellipse'></SvgIcon>
            <div style={{ color: "#1D2129", fontSize: "20px", fontWeight: "bold", marginLeft: "10px" }}>高频词云</div>
          </div>

          {wordFreqLoading ? (
            <Skeleton active paragraph={{ rows: 8 }} style={{ padding: '10px' }} />
          ) : (
            <WordCloudChart data={wordCloudData} />
          )}
        </div> */}
      </div>

      <div className={`${isPc ? 'flex' : ''}`}>
        <div
          style={{
            marginRight: '20px',
            padding: '20px 20px',
            marginTop: '16px',
            backgroundColor: '#FBFCFF',
            borderRadius: '20px',
            width: '100%',
            height: '500px',
          }}
        >
          {zhaosDashboardActiveLoading ? (
            <Skeleton active paragraph={{ rows: 8 }} />
          ) : (
            <div className="h-full">
              <div className="flex items-center justify-between">
                <div className="flex items-center">
                  <SvgIcon color="#1B6DFA" icon="Ellipse" />
                  <div
                    style={{
                      color: '#1D2129',
                      fontSize: '20px',
                      fontWeight: 'bold',
                      marginLeft: '10px',
                    }}
                  >
                    近24小时用户活跃情况
                  </div>
                </div>
                {/* <SvgIcon icon="Vector" color='black' onClick={() => { setLogoutVisible(true) }} size={35} /> */}
                <FullscreenOutlined
                  onClick={() => {
                    setLogoutVisible(true);
                  }}
                  size={35}
                />
              </div>
              <UserActiveStatuLine data={getLast24HoursData(dashboardActive)} />
            </div>
          )}
        </div>
        <div
          style={{
            padding: '20px 20px',
            marginTop: '16px',
            backgroundColor: '#FBFCFF',
            borderRadius: '20px',
            width: '100%',
            height: '500px',
          }}
        >
          {zhaoshengLoading ? (
            <Skeleton active paragraph={{ rows: 8 }} />
          ) : (
            <div className="h-full">
              <div className="flex items-center justify-between">
                <div className="flex items-center">
                  <SvgIcon color="#1B6DFA" icon="Ellipse" />
                  <div
                    style={{
                      color: '#1D2129',
                      fontSize: '20px',
                      fontWeight: 'bold',
                      marginLeft: '10px',
                    }}
                  >
                    学校咨询量统计
                  </div>
                </div>

                {/* <SvgIcon icon="Vector" onClick={() => { setHighschoolBarVisible(true) }} color='black' size={35} /> */}
                <FullscreenOutlined
                  onClick={() => {
                    setHighschoolBarVisible(true);
                  }}
                  size={35}
                />
              </div>
              <ConsultationStatisticsBar
                data={
                  highschoolConsultations.length > 8
                    ? highschoolConsultations.slice(0, 8)
                    : highschoolConsultations
                }
              />
            </div>
          )}
        </div>
      </div>

      <div
        style={{
          padding: '20px 20px',
          marginTop: '16px',
          backgroundColor: '#FBFCFF',
          borderRadius: '20px',
          width: '100%',
          height: '500px',
        }}
      >
        <div>
          <div className="flex items-center justify-between">
            <div className="flex items-center">
              <SvgIcon color="#1B6DFA" icon="Ellipse" />
              <div
                style={{
                  color: '#1D2129',
                  fontSize: '20px',
                  fontWeight: 'bold',
                  marginLeft: '10px',
                }}
              >
                历史提问
              </div>
            </div>
            <Input
              style={{ width: isPc ? '300px' : '200px' }}
              placeholder="问题关键词"
              onChange={(e) => setSearchHotwords(e.target.value)}
              prefix={<SearchOutlined />}
            />
          </div>

          {isPc ? (
            <Space
              className="mt-4"
              style={{ width: '100%', overflow: 'auto', scrollbarWidth: 'none' }}
            >
              {Array.isArray(hotwords) &&
                hotwords.map((item, index) => (
                  // <Button shape="round" key={index} type={"primary"} onClick={() => changeHotword(item.word)} >{item.word}</Button>
                  <Button
                    shape="round"
                    key={index}
                    type={Achotwords == item.label ? 'primary' : 'default'}
                    onClick={() => changeHotword(item.label)}
                  >
                    {item.label}
                  </Button>
                ))}
            </Space>
          ) : (
            <Button
              onClick={() => {
                setVisiblemobile(true);
              }}
              style={{ width: '100%', marginTop: '8px' }}
            >
              选择
            </Button>
          )}

          <Picker
            columns={[hotwords]}
            visible={visiblemobile}
            onClose={() => {
              setVisiblemobile(false);
            }}
            value={value}
            onConfirm={(v) => {
              // setValue(v)
              console.log('vvv============', v, hotwords);

              changeHotword(v[0]);
            }}
          />
          {historyQuestions && historyQuestions.length > 0 ? (
            <div style={{ height: '375px', overflowY: 'auto' }}>
              {historyQuestions &&
                historyQuestions.map((item, index) => (
                  <div className="pb-3 pt-3" style={{ borderBottom: '1px solid #E5E5E5' }}>
                    <p className="text-[14px] leading-[30px]">{item.question}</p>
                    <div className="flex">
                      <p className="mr-8 text-[12px] leading-[20px] text-[#86909C]">
                        提问人: {item.usr_name}
                      </p>
                      <p className="text-[12px] leading-[20px] text-[#86909C]">
                        {' '}
                        {(() => {
                          const date = new Date(item.create_time);
                          date.setHours(date.getHours() + 8);
                          return date.toLocaleString();
                        })()}
                      </p>
                    </div>
                  </div>
                ))}
            </div>
          ) : (
            <Empty description="暂无数据" />
          )}
        </div>
      </div>

      <UserActiveStatuLineModel
        visible={logoutVisible}
        text="实时用户活跃情况"
        onCancel={() => {
          setLogoutVisible(false);
        }}
        data={dashboardActive}
        onConfirm={handleLogoutConfirm}
      />

      <HighschoolBarModel
        visible={highschoolBarVisible}
        text="学校咨询量统计"
        onCancel={() => {
          setHighschoolBarVisible(false);
        }}
        data={highschoolConsultations}
        onConfirm={handleLogoutConfirm}
      />
    </div>
  );
};

export default Report2;
